import DeptAPI from "@/api/dept"
import RoleAPI from "@/api/role"
import UserRoleAPI, { UserRoleForm } from "@/api/user-role"
import UserAPI, { UserForm } from "@/api/user"
import type { IModalConfig } from "@/components/CURD/types"
import { buildSelect, buildTreeSelect } from "@/utils"

import { useDict } from "@/utils/dict"
const { gender, user_status } = toRefs<any>(useDict("gender", "user_status"))

const formModalConfig: IModalConfig<UserForm> = {
  component: "dialog",
  pageName: "user",
  modal: {
    title: "用户表单",
    width: 800,
    draggable: true,
  },
  form: {
    labelWidth: 100,
  },
  pk: "user_id",
  formAction: async function (data) {
    console.log("表单提交", data)
    let userId = data.user_id
    if (userId) {
      //1、先更新
      await UserAPI.update(data)
    } else {
      //1、先新增
      const res = await UserAPI.add(data)
      if (res.data) {
        userId = res.data.user_id
      }
    }
    //2、删除 users_roles
    const deleteCondition: QueryCondition = {
      _cond: {
        and: [{ field: "user_id", op: "=", value: userId }],
      },
    }
    await UserRoleAPI.deleteBy(deleteCondition)
    //3、新增 users_roles
    if (data.role_ids) {
      const userRoleList: UserRoleForm[] = []
      data.role_ids.forEach((role_id: number) => {
        userRoleList.push({
          user_id: userId as number,
          role_id: role_id,
        })
      })
      UserRoleAPI.saveBatch(userRoleList)
    }
    return Promise.resolve({})
  },
  beforeSubmit(data) {
    console.log("提交之前处理", data)
  },
  formItems: [
    {
      label: "用户名",
      prop: "username",
      rules: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
      type: "input",
      attrs: {
        placeholder: "请输入用户名",
      },
    },
    {
      label: "密码",
      prop: "password",
      slotName: "password",
      rules: [{ required: false, message: "密码不能为空", trigger: "blur" }],
      type: "custom",
      attrs: {
        placeholder: "请输入密码",
        showPassword: true,
      },
    },
    {
      label: "用户昵称",
      prop: "nick_name",
      rules: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
      type: "input",
      attrs: {
        placeholder: "请输入用户昵称",
      },
    },
    {
      label: "所属部门",
      prop: "dept_id",
      rules: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
      type: "tree-select",
      attrs: {
        placeholder: "请选择所属部门",
        data: [],
        filterable: true,
        "check-strictly": true,
        "render-after-expand": false,
      },
      async initFn(formItem) {
        const res = await DeptAPI.query()
        if (res.status === 200) {
          formItem.attrs.data = buildTreeSelect(res.data, "dept_id", "pid", "dept_id", "name")
        }
      },
    },
    {
      type: "dict",
      label: "性别",
      prop: "gender",
      options: gender,
    },
    {
      label: "角色",
      prop: "role_ids",
      rules: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
      type: "select",
      attrs: {
        placeholder: "请选择",
        multiple: true,
      },
      options: [],
      async initFn(formItem) {
        const res = await RoleAPI.query()
        if (res.status === 200 && res.data) {
          this.options = buildSelect(res.data, "role_id", "name")
        }
      },
    },
    {
      type: "input",
      label: "手机号码",
      prop: "phone",
      rules: [
        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur",
        },
      ],
      attrs: {
        placeholder: "请输入手机号码",
        maxlength: 11,
      },
    },
    {
      label: "邮箱",
      prop: "email",
      rules: [
        {
          pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
          message: "请输入正确的邮箱地址",
          trigger: "blur",
        },
      ],
      type: "input",
      attrs: {
        placeholder: "请输入邮箱",
        maxlength: 50,
      },
    },
    {
      label: "状态",
      prop: "enabled",
      type: "dict",
      options: user_status,
    },
  ],
}

export default formModalConfig
